package com.xishu.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    private static Logger logger = LoggerFactory.getLogger(AES.class);

    private static final byte[] key = "1230987654abcdef".getBytes();//key.length须满足16的整数倍
    private static final byte[] iv = "1230987654abcdef".getBytes();//iv.length须满足16的整数倍
    private static final String transform = "AES/CBC/PKCS5Padding";

    public static String encrypt(String content) {
        try {
            Cipher cipher = Cipher.getInstance(transform);

            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

            cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
            byte[] cipherData = cipher.doFinal(content.getBytes("UTF-8"));
            return Hex.encodeHexString(cipherData);
        } catch (Exception e) {
            logger.debug("e", e);
        }

        return StringUtils.EMPTY;
    }

    public static String decrypt(String content) {
        try {
            Cipher cipher = Cipher.getInstance(transform);
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
            byte[] decrypt = cipher.doFinal(Hex.decodeHex(content));
            return new String(decrypt);
        } catch (Exception e) {
            logger.debug("e", e);
        }

        return StringUtils.EMPTY;
    }

    public static byte[] decrypt(String content, byte[] key, byte[] iv) {
        try {
            Cipher cipher = Cipher.getInstance(transform);

            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

            cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
            byte[] cipherData = cipher.doFinal(content.getBytes("UTF-8"));
            return cipherData;
        } catch (Exception e) {
            logger.debug("e", e);
        }

        return new byte[0];
    }

    public static byte[] decrypt(byte[] contents, byte[] key, byte[] iv) {
        try {
            Cipher cipher = Cipher.getInstance(transform);

            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

            cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
            byte[] cipherData = cipher.doFinal(contents);
            return cipherData;
        } catch (Exception e) {
            logger.debug("e", e);
        }

        return new byte[0];
    }

    public static String decryptBase64(String contents, byte[] key, byte[] iv) {
        byte[] decodeBase64 = Base64.decodeBase64(contents);
        byte[] decrypt = decrypt(decodeBase64, key, iv);
        return new String(decrypt);
    }




}
